package com.briup.mr;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapred.lib.db.DBConfiguration;
import org.apache.hadoop.mapred.lib.db.DBOutputFormat;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.TextInputFormat;
import org.apache.hadoop.mapreduce.lib.map.TokenCounterMapper;
import org.apache.hadoop.mapreduce.lib.reduce.IntSumReducer;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;

import java.io.IOException;

/**
 * @author adam
 * @date 2023/5/31
 */
public class WordCountToMysql extends Configured implements Tool {


    public static  class WordCountToMysqlReducer extends Reducer<Text,IntWritable,WordNum, NullWritable>{
        @Override
        protected void reduce(Text key, Iterable<IntWritable> values, Reducer<Text, IntWritable, WordNum, NullWritable>.Context context) throws IOException, InterruptedException {
            int sum=0;
            for (IntWritable value : values) {
                sum+=value.get();
            }
            WordNum wordNum = new WordNum(key.toString(), sum);
            context.write(wordNum,NullWritable.get());
        }
    }
    @Override
    public int run(String[] args) throws Exception {

        Configuration conf = getConf();
//        String in = conf.get("in");

        Path inPath = new Path("hdfs://server:9000/gsau/xyz/word.txt");

//        创建数据配置  保证能连接到数据库
        DBConfiguration.configureDB(conf,"com.mysql.cj.jdbc.Driver","jdbc:mysql://127.0.0.1:3306/briup","root","root");


        Job job = Job.getInstance(conf);
        job.setJobName("词频统计 将结果输出保存到mysql");
        job.setJarByClass(this.getClass());
        job.setInputFormatClass(TextInputFormat.class);
        TextInputFormat.setInputPaths(job,inPath);
        job.setMapperClass(TokenCounterMapper.class);
        job.setMapOutputKeyClass(Text.class);
        job.setMapOutputValueClass(IntWritable.class);
        job.setNumReduceTasks(1);
        job.setReducerClass(WordCountToMysqlReducer.class);
        job.setOutputKeyClass(WordNum.class);
        job.setOutputValueClass(NullWritable.class);

        job.setOutputFormatClass(DBOutputFormat.class);
        DBOutputFormat.setOutput(job,"wordcount","word","num");

        return job.waitForCompletion(true)?0:-1;
    }

    public static void main(String[] args) {
        try {
            ToolRunner.run(new WordCountToMysql(),args);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
